/*
 * Copyright 2011 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.gaellalire.jzip.test.macosx;

import java.awt.Cursor;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Point;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragSourceContext;
import java.awt.dnd.InvalidDnDOperationException;
import java.awt.dnd.peer.DragSourceContextPeer;
import java.awt.peer.FramePeer;
import java.io.File;
import java.util.List;

import org.rococoa.ID;
import org.rococoa.Rococoa;
import org.rococoa.cocoa.foundation.NSString;

import apple.awt.CFrame;
import apple.awt.CToolkit;

@SuppressWarnings({"restriction", "unused"})
public class ToolkitHook extends apple.awt.CToolkit {

    private static CToolkit cToolkit = new CToolkit();

//    @Override
//    public WindowPeer createWindow(Window arg0) {
//        throw new RuntimeException();
//        // need to change NSView to intercept drag calls
////        return new CWindowHook(arg0);
//    }

    @Override
    public FramePeer createFrame(final Frame arg0) {
        CFrame create = CFrame.create(arg0);
        ID id = ID.fromLong(create.getViewPtr());
        NSView wrap = Rococoa.wrap(id, NSView.class);
       ID oldDelegate = wrap.window().delegate();
       wrap.window().setDelegate(new WindowDelegateHook(Rococoa.wrap(oldDelegate, NSWindowDelegate.class)).id());
    System.out.println("OLD : " + oldDelegate);
    System.out.println("NEW: " + wrap.window().delegate());

        wrap.window().center();
        System.out.println("hid "+wrap.isHidden());
        return create;
    }

    @Override
    public DragSourceContextPeer createDragSourceContextPeer(final DragGestureEvent dge) throws InvalidDnDOperationException {
        if(true) {
          //  SunDropTargetContextPeer.setCurrentJVMLocalSourceTransferable
            return cToolkit.createDragSourceContextPeer(dge);
        }

        System.out.println(dge.getDragSource().getFlavorMap().getNativesForFlavors(null));
       // dge.startDrag(dragCursor, transferable)
       // throw new InvalidDnDOperationException();
        return new DragSourceContextPeer() {

            @Override
            public void transferablesFlavorsChanged() {
                // TODO Auto-generated method stub

            }

            @Override
            public void startDrag(final DragSourceContext dsc, final Cursor c, final Image dragImage, final Point imageOffset) throws InvalidDnDOperationException {
            }

            @Override
            public void setCursor(final Cursor c) throws InvalidDnDOperationException {

            }

            @Override
            public Cursor getCursor() {
                return null;
            }
        };
//        System.out.println(event);
//        if(event != null) {
//
//            event.
//            dragPosition = [self convertPoint:[theEvent locationInWindow]
//                                               fromView:nil];
//                           dragPosition.x -= 16;
//                           dragPosition.y -= 16;
//                           imageLocation.origin = dragPosition;
//                           imageLocation.size = NSMakeSize(32,32);
//                           [self dragPromisedFilesOfTypes:[NSArray arrayWithObject:@"pdf"]
//                                   fromRect:imageLocation
//                                   source:self
//                                   slideBack:YES
//                                   event:theEvent];
//
//            NSWindow window = event.window();
//            window.contentView().dragPromisedFilesOfTypes(typeArray, rect, sourceObject, slideBack, event)
//            System.out.println(event.locationInWindow().getPoint());
//        }
//
//        return super.createDragSourceContextPeer(dge);
    }
//
//    @Override
//    public WindowPeer createWindow(Window arg0) {
//        return super.createWindow(arg0);
//    }
//
    public boolean writeItemsToPasteBoard(final NSView view, final List<String> items) {
        // The fileTypes argument is the list of fileTypes being promised.
        // The array elements can consist of file extensions and HFS types
        // encoded
        // with the NSHFSFileTypes method fileTypeForHFSTypeCode. If promising a
        // directory
        // of files, only include the top directory in the array.
        final NSMutableArray fileTypes = NSMutableArray.array();
        for (String item : items) {
            File path = new File("/cocoa.txt");
            if (path.isFile()) {
                if (true) {
                    fileTypes.addObject(NSString.stringWithString("txt"));
                } else {
                    fileTypes.addObject(NSString.stringWithString(NSFileManager.NSFileTypeRegular));
                }
            } else if (path.isDirectory()) {
                fileTypes.addObject(NSString.stringWithString("'fldr'")); // NSFileTypeForHFSTypeCode('fldr')
            } else {
                fileTypes.addObject(NSString.stringWithString(NSFileManager.NSFileTypeUnknown));
            }
        }
        /*
        NSEvent event = NSApplication.sharedApplication().currentEvent();
        if (event != null) {
            NSPoint dragPosition = view.convertPoint_fromView(event.locationInWindow(), null);
            NSRect imageRect = new NSRect(new NSPoint(dragPosition.x.doubleValue() - 16, dragPosition.y.doubleValue() - 16), new NSSize(32, 32));
            // draggingSourceOperationMask
            view.dragPromisedFilesOfTypes(fileTypes, imageRect, new DragProvider().id(), true, event);
            // @see
            // http://www.cocoabuilder.com/archive/message/cocoa/2003/5/15/81424
            return true;
        }
        */
        return false;
    }
//
//    /**
//     * @return the names (not full paths) of the files that the receiver promises to create at dropDestination.
//     *         This method is invoked when the drop has been accepted by the destination and the destination, in the case of another
//     *         Cocoa application, invokes the NSDraggingInfo method namesOfPromisedFilesDroppedAtDestination. For long operations,
//     *         you can cache dropDestination and defer the creation of the files until the finishedDraggingImage method to avoid
//     *         blocking the destination application.
//     */
//    public NSArray namesOfPromisedFilesDroppedAtDestination(final NSURL url) {
//        NSMutableArray promisedDragNames = NSMutableArray.array();
//        if(null != url) {
//            final Local destination = LocalFactory.createLocal(url.path());
//            final PathPasteboard pasteboard = PathPasteboard.getPasteboard(controller.getSession());
//            for(Path p : pasteboard) {
//                p.setLocal(LocalFactory.createLocal(destination, p.getName()));
//                // Add to returned path names
//                promisedDragNames.addObject(NSString.stringWithString(p.getLocal().getName()));
//            }
//            if(pasteboard.size() == 1) {
//                if(pasteboard.get(0).attributes().isFile()) {
//                    pasteboard.get(0).getLocal().touch();
//                }
//                if(pasteboard.get(0).attributes().isDirectory()) {
//                    pasteboard.get(0).getLocal().mkdir();
//                }
//            }
//            final boolean dock = destination.equals(LocalFactory.createLocal("~/Library/Caches/TemporaryItems"));
//            DownloadTransfer transfer = new DownloadTransfer(pasteboard.copy(controller.getTransferSession())) {
//                @Override
//                protected void fireDidTransferPath(Path path) {
//                    if(dock) {
//                        WatchEditor editor = new WatchEditor(controller, path);
//                        editor.watch();
//                    }
//                    super.fireDidTransferPath(path);
//                }
//            };
//            if(dock) {
//                // Drag to application icon in dock.
//                controller.transfer(transfer, new TransferPrompt() {
//                    public TransferAction prompt() {
//                        return TransferAction.ACTION_OVERWRITE;
//                    }
//                });
//            }
//            else {
//                controller.transfer(transfer);
//            }
//            pasteboard.clear();
//        }
//        // Filenames
//        return promisedDragNames;
//    }


}
